package com.xgst.land.utils

import android.content.Context.AUDIO_SERVICE
import android.media.AudioManager
import android.media.SoundPool
import com.xgst.land.App
import com.xgst.land.R

object SoundUtils {
    private var soundPool = SoundPool(2, AudioManager.STREAM_MUSIC, 0)
    private var soundMap = mutableMapOf<Int, Int>()
    private var am:AudioManager
    private var volumnRatio = 0f
    const val SOUND_SUCCESS = 1
    const val SOUND_ERROR = 2
    const val CHECK_SUCCESS = 3
    const val CHECK_ERROR = 4
    //距离超窗还有30秒
    const val OUT_OF_WINDOW30 = 5
    //距离计划采样时间还有30秒
    const val AFTER_COLLECTION = 6
    //请立即采样
    const val COLLECTION_BLOOD = 7
    //已超窗 填写备注
    const val OUT_OF_WINDOW = 8
    //已记录时间
    const val RECORD_TIME = 9
    //已进入时间窗，做好相关准备
    const val WINDOW_BEGIN = 10

    init {
        soundMap[1] = soundPool.load(App.context, R.raw.barcodebeep, 1)
        soundMap[2] = soundPool.load(App.context, R.raw.serror, 1)
        soundMap[3] = soundPool.load(App.context, R.raw.check_96_success, 1)
        soundMap[4] = soundPool.load(App.context, R.raw.check_96_error, 1)

        soundMap[5] = soundPool.load(App.context, R.raw.after_outof_window30, 1)
        soundMap[6] = soundPool.load(App.context, R.raw.after_collection_blood30, 1)
        soundMap[7] = soundPool.load(App.context, R.raw.collection_blood, 1)
        soundMap[8] = soundPool.load(App.context, R.raw.outof_window, 1)
        soundMap[9] = soundPool.load(App.context, R.raw.recording_time, 1)
        soundMap[10] = soundPool.load(App.context, R.raw.window_begin, 1)
        am = App.context?.getSystemService(AUDIO_SERVICE) as AudioManager
    }

    //在Splash界面提前加载声音文件
    fun load(){
        val audioMaxVolumn =
            am.getStreamMaxVolume(AudioManager.STREAM_MUSIC).toFloat() // 返回当前AudioManager对象的最大音量值
        val audioCurrentVolumn =
            am.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat() // 返回当前AudioManager对象的音量值
        volumnRatio = audioCurrentVolumn / audioMaxVolumn
    }

    fun playSound(id: Int) {
        try {
            soundPool.play(
                soundMap[id]!!, volumnRatio,  // 左声道音量
                volumnRatio,  // 右声道音量
                1,  // 优先级，0为最低
                0, 1f
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}